import { FC, useState, useEffect, useRef } from "react";
import EditCanvas from "./EditCanvas";
import LeftPanel from "./LeftPanel";
import RightPanel from "./RightPanel";
import EditHeader from "./EditHeader";
import useLoadQuestionData from "../../../hooks/useLoadQuestionData";
import { changeSelectId } from "@/store/componentReducer";
import { useDispatch } from "react-redux";

const Edit: FC = () => {
  const { loading } = useLoadQuestionData();
  const dispatch = useDispatch();

  const [scale, setScale] = useState(1);
  const containerRef = useRef<HTMLDivElement>(null);
  const canvasRef = useRef<HTMLDivElement>(null);
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const [isDragging, setIsDragging] = useState(false);
  const [isSpacePressed, setIsSpacePressed] = useState(false);
  const [startPos, setStartPos] = useState({ x: 0, y: 0 });

  function clearSelectId() {
    dispatch(changeSelectId(""));
  }

  // 处理键盘事件
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.code === "Space" && !isSpacePressed) {
        e.preventDefault();
        setIsSpacePressed(true);
        document.body.style.cursor = "grab";
      }
    };

    const handleKeyUp = (e: KeyboardEvent) => {
      if (e.code === "Space") {
        setIsSpacePressed(false);
        document.body.style.cursor = "default";
      }
    };

    window.addEventListener("keydown", handleKeyDown);
    window.addEventListener("keyup", handleKeyUp);

    return () => {
      window.removeEventListener("keydown", handleKeyDown);
      window.removeEventListener("keyup", handleKeyUp);
      document.body.style.cursor = "default";
    };
  }, [isSpacePressed]);

  // 处理鼠标事件
  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    const handleMouseDown = (e: MouseEvent) => {
      if (isSpacePressed) {
        e.preventDefault();
        setIsDragging(true);
        document.body.style.cursor = "grabbing";
        setStartPos({
          x: e.clientX - position.x,
          y: e.clientY - position.y,
        });
      }
    };

    const handleMouseMove = (e: MouseEvent) => {
      if (isDragging && isSpacePressed) {
        setPosition({
          x: e.clientX - startPos.x,
          y: e.clientY - startPos.y,
        });
      }
    };

    const handleMouseUp = () => {
      if (isDragging) {
        setIsDragging(false);
        document.body.style.cursor = isSpacePressed ? "grab" : "default";
      }
    };

    container.addEventListener("mousedown", handleMouseDown);
    window.addEventListener("mousemove", handleMouseMove);
    window.addEventListener("mouseup", handleMouseUp);

    return () => {
      container.removeEventListener("mousedown", handleMouseDown);
      window.removeEventListener("mousemove", handleMouseMove);
      window.removeEventListener("mouseup", handleMouseUp);
    };
  }, [isDragging, isSpacePressed, position, startPos]);

  // 处理缩放
  useEffect(() => {
    const container = containerRef.current;
    const canvas = canvasRef.current;
    if (!container || !canvas) return;

    const handleWheel = (e: WheelEvent) => {
      if (e.ctrlKey || e.metaKey) {
        e.preventDefault();
        const canvasRect = canvas.getBoundingClientRect();
        const mouseX = e.clientX - canvasRect.left;
        const mouseY = e.clientY - canvasRect.top;
        const centerX = canvasRect.width / 2;
        const centerY = canvasRect.height / 2;
        const offsetX = (mouseX - centerX) / scale;
        const offsetY = (mouseY - centerY) / scale;

        const delta = e.deltaY;
        const newScale =
          delta < 0 ? Math.min(scale + 0.1, 2) : Math.max(scale - 0.1, 0.3);

        const scaleDiff = newScale - scale;
        const newPosition = {
          x: position.x - offsetX * scaleDiff,
          y: position.y - offsetY * scaleDiff,
        };

        setScale(newScale);
        setPosition(newPosition);
      }
    };

    container.addEventListener("wheel", handleWheel, { passive: false });
    return () => container.removeEventListener("wheel", handleWheel);
  }, [scale, position]);

  return (
    <div className="flex flex-col h-screen min-w-[1300px] bg-[#f0f2f5]">
      <div className="bg-white h-11">
        <EditHeader />
      </div>
      <div className="flex-auto py-4">
        <div className="mx-6 flex h-full">
          <div className="w-100 bg-white px-3">
            <LeftPanel />
          </div>
          <div
            ref={containerRef}
            className={`flex-1 bg-gray-100 px-3 relative overflow-hidden ${
              isSpacePressed ? "cursor-grab" : ""
            } ${isDragging ? "cursor-grabbing" : ""}`}
            onClick={!isSpacePressed ? clearSelectId : undefined}
          >
            <div
              ref={canvasRef}
              className="absolute top-1/2 left-1/2 w-100 h-200 -translate-x-1/2 -translate-y-1/2 overflow-auto shadow-lg"
              style={{
                transform: `
                  translate(${position.x}px, ${position.y}px)
                  scale(${scale})
                `,
                transformOrigin: "center center",
                transition: isDragging ? "none" : "transform 0.1s ease-out",
              }}
            >
              <EditCanvas loading={loading} />
            </div>
          </div>
          <div className="w-90 bg-white px-3">
            <RightPanel />
          </div>
        </div>
      </div>
    </div>
  );
};

export default Edit;
